package apps.softtech.fastmarket;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import apps.softtech.Utility.ConnectionDetector;
import apps.softtech.Utility.HttpRequest;
import apps.softtech.Utility.RequestDataFromServer;
import apps.softtech.fastmarket.adapter.AdapterSearchResult;
import apps.softtech.fastmarket.model.DatabaseHandler;
import apps.softtech.fastmarket.model.Product;

@SuppressLint("NewApi")
public class ActivitySearch extends Activity {
	protected static final String URL_PRODUCT_REQUEST = "http://softtech.vn/fastmarket/index.php/product/get_product_by_user_id";
	protected static final String TAG = null;
	ListView lvSearchResult;
	AutoCompleteTextView etSearchProducts;
	Button btSearchProducts;
	AdapterSearchResult mAdapterSearchResult;
	ArrayList<Product> mProductsList = new ArrayList<Product>();
	DatabaseHandler dbh;
	private ArrayAdapter<String> adapterAuto;
	private Context mContext;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_search);
		Intent intent = getIntent();
		String gcmId = intent.getStringExtra("gcmId");
		String userId = intent.getStringExtra("userId");
		if (userId.equals("") || userId.equals(null)) {
			ConnectionDetector detector = new ConnectionDetector(mContext);
			if (detector.isConnectingToInternet()) {
				// load product by userid if have internet
				getProductByUser(gcmId, userId);
			} else {
				// do something if no internet connection
				Toast.makeText(mContext, "Internet is not avaiable",
						Toast.LENGTH_LONG).show();
			}

		} else {
			// test add array

			insert();

			init();

			initFunction();
		}

	}

	/**
	 * array
	 */
	String[] Constant = { "so1", "so2", "so3", "so4", "soxx", "2" };

	private void insert() {

	}

	/**
	 * init id
	 */
	private void init() {
		dbh = new DatabaseHandler(ActivitySearch.this);
		etSearchProducts = (AutoCompleteTextView) findViewById(R.id.actvSearchProducts);
		btSearchProducts = (Button) findViewById(R.id.btSearchProducts);
		lvSearchResult = (ListView) findViewById(R.id.lvSearchProduct);
		adapterAuto = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, Constant);
		etSearchProducts.setAdapter(adapterAuto);
		// firt key
		etSearchProducts.setThreshold(1);
	}

	/**
	 * init function
	 */
	private void initFunction() {

		etSearchProducts.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {

			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {

			}

			@Override
			public void afterTextChanged(Editable arg0) {
				content = etSearchProducts.getText().toString().trim();
				if (content.equals("") || content.equals(null)) {
					mProductsList.clear();
					setData();
				}

			}
		});
//		etSearchProducts.setOnItemClickListener(new OnItemClickListener() {
//
//			@Override
//			public void onItemClick(AdapterView<?> parent, View arg1,
//					int position, long arg3) {
//				content = (String) parent.getItemAtPosition(position);
//				;
//				if (content.equals("") || content.equals(null)) {
//			public void onItemClick(AdapterView<?> parent, View arg1, int position,
//					long arg3) {
//				content = (String) parent.getItemAtPosition(position);
//				if(content.equals("") ||  content.equals(null)){
//					mProductsList.clear();
//					setData();
//				} else {
//					mProductsList = (ArrayList<Product>) dbh.getProduct(null,
//							Product.CATEGORY_ID + " LIKE ?", new String[] { "%"
//									+ content + "%" }, Product.PRODUCT_ID
//									+ " DESC", null);
//					if (mProductsList.size() != 0) {
//						setData();
//					}
//				}
//			}
//		});
		btSearchProducts.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				content = etSearchProducts.getText().toString().trim();
				if (content.equals("") || content.equals(null)) {
					return;
				}

				// mProductsList = (ArrayList<Product>) dbh.getProduct(null,
				// Product.CATEGORY_ID + " =?",
				// new String[]{"%"+content+"%"},Product.PRODUCT_ID + " DESC",
				// null);
				// if(mProductsList.size()!=0){
				// setData();
				// }else{
				//
				// }
				new AsyncTaskGetProductSearch().execute();
			}
		});

	}

	/**
	 * content to search
	 */

	String content;
	protected ProgressDialog progress;

	/**
	 * setup data
	 */
	private void setData() {
		mAdapterSearchResult = new AdapterSearchResult(mProductsList,
				ActivitySearch.this);
		lvSearchResult.setAdapter(mAdapterSearchResult);
	}

	@Override
	protected void onDestroy() {
		dbh.close();
		super.onDestroy();
	}

	class AsyncTaskGetProductSearch extends AsyncTask<Void, Void, Void> {
		ProgressDialog pd;

		@Override
		protected void onPreExecute() {
			pd = new ProgressDialog(ActivitySearch.this);
			pd.setMessage("Searching.......");
			pd.show();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO request search
			// new RequestDataFromServer().requestProductsByName(NameProduct)
			// TODO request search
			new RequestDataFromServer().requestProductsByName(content);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			mProductsList = (ArrayList<Product>) dbh.getProduct(null,
					Product.CATEGORY_ID + " =?", new String[] { "%" + content
							+ "%" }, Product.PRODUCT_ID + " DESC", null);
			if (mProductsList.size() != 0) {
				setData();
			}
			pd.dismiss();
			super.onPostExecute(result);
		}
	}

	@SuppressWarnings("unused")
	private void searchProductByUser() {

	}

	@SuppressWarnings("unused")
	private void initListProductUser(JSONObject json) {

		for (int i = 0; i < json.length(); i++) {

		}

	}

	@SuppressWarnings({ "unchecked", "unused" })
	private void getProductByUser(String gcmId, String userId) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		JSONObject jsonOject = new JSONObject();

		try {
			jsonOject.put("st_GcmId", gcmId);
			jsonOject.put("st_UserId", userId);

		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		params.add(new BasicNameValuePair("data", jsonOject.toString()));

		new AsyncTask<List<NameValuePair>, Void, String>() {

			protected void onPreExecute() {
				progress = new ProgressDialog(ActivitySearch.this);
				progress.setMessage("Getting ...");
				progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				progress.setIndeterminate(true);
				progress.show();
			};

			@Override
			protected String doInBackground(List<NameValuePair>... params) {
				HttpRequest request = new HttpRequest();
				String result = request.makeServiceCall(URL_PRODUCT_REQUEST,
						HttpRequest.POST, params[0]);
				try {
					JSONObject jsonProduct = new JSONObject(result);

					if (jsonProduct.getString("success") != null) {
						String check = jsonProduct.getString("success");
						if (Integer.parseInt(check) != 0) {

							return result;
						} else { //
							if (Integer.parseInt(check) == 0) {
								return "";
							}
						}
					} else {
						Log.i(TAG, "success null");
						return "";
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
				return "";
			}

			@Override
			protected void onPostExecute(String result) {
				super.onPostExecute(result);
				progress.hide();
				if (!result.equals("")) {
					try {
						JSONArray jsonArr = new JSONArray(result);
						for (int i = 0; i < jsonArr.length(); i++) {
							Product product = new Product();
							JSONObject obj = jsonArr.getJSONObject(i);
							product.setAvatarPath(obj.getString("st_AvatarPath"));
							mProductsList.add(product);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}

				} else if (result.equals("")) {
					Toast.makeText(getApplicationContext(), "chua dc",
							Toast.LENGTH_SHORT).show();
				}
			}
		}.execute(params, null, null);
		mAdapterSearchResult = new AdapterSearchResult(mProductsList, mContext);
		lvSearchResult.setAdapter(mAdapterSearchResult);

	}
}
